﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input; 
using Microsoft.Practices.Prism.Commands;
using ZhiHeng.Consume.DataContract;
using ZhiHeng.OneCard.WpfClient.Common;
using ZhiHeng.OneCard.WpfClient.Model;
using DevComponents.WPF.Controls;
using System.Collections.ObjectModel; 

namespace ZhiHeng.OneCard.WpfClient.ViewModel
{
    public class DictManagerViewModel : ViewModelBase
    {
        //选中的节点
        private TreeViewEntity _selectData;

        public TreeViewEntity SelectData
        {
            get { return _selectData; }
            set
            {
                _selectData = value;
                if (_selectData != null)
                {
                    TempInfo.Name = ((ConfigTreeInfo)SelectData.Data).Name;
                    TempInfo.Code = ((ConfigTreeInfo)SelectData.Data).Code;
                    TempInfo.Content = ((ConfigTreeInfo)SelectData.Data).Content;
                    TempInfo.Type = ((ConfigTreeInfo)SelectData.Data).Type;
                    TempInfo.AssistantCode = ((ConfigTreeInfo)SelectData.Data).AssistantCode;
                    TempInfo.IsUpdate = ((ConfigTreeInfo)SelectData.Data).IsUpdate;
                    if (((ConfigTreeInfo)SelectData.Data).Type == -1)
                    {
                        Types = Datas.Where(p => p.Type == TempInfo.Code);
                        TempInfo.Type = TempInfo.Code;
                        TempInfo.Name = "";
                    }
                    else
                    {
                        Types = Datas.Where(p => p.Type == TempInfo.Type && p.Code == TempInfo.Code).OrderBy(p => p.Type);
                    }
                }
                RaisePropertyChanged("SelectData");
            }
        }

        //临时数据
        private ConfigTreeInfo _tempinfo;

        public ConfigTreeInfo TempInfo
        {
            get
            {
                if (_tempinfo == null)
                {
                    _tempinfo = new ConfigTreeInfo();
                    _tempinfo.IsUpdate = true;
                }
                return _tempinfo;
            }
            set
            {
                _tempinfo = value;
                if (_selectData != null)
                {

                }
                RaisePropertyChanged("TempInfo");
            }
        }


        private IEnumerable<ConfigTreeInfo> Datas;

        private ObservableCollection<TreeViewEntity> _nodedatas;

        public ObservableCollection<TreeViewEntity> NodeDatas
        {
            get { return _nodedatas; }
            set
            {
                _nodedatas = value;
                RaisePropertyChanged("NodeDatas");
            }
        }


        private ObservableCollection<TreeViewEntity> _nodes;

        public ObservableCollection<TreeViewEntity> Nodes
        {
            get { return _nodes; }
            set
            {
                _nodes = value;
                RaisePropertyChanged("Nodes");
            }
        }



        private IEnumerable<ConfigTreeInfo> _types;

        public IEnumerable<ConfigTreeInfo> Types
        {
            get { return _types; }
            set
            {
                _types = value;
                RaisePropertyChanged("Types");
            }
        }

        private Dictionary<string, int> _typesenum;

        public Dictionary<string, int> TypesEnum
        {
            get
            {
                if (_typesenum == null)
                {
                    _typesenum = new Dictionary<string, int>();
                    foreach (int myCode in Enum.GetValues(typeof(StaticDicdictionary.TypeDicdictionary)))
                    {
                        string strName = Enum.GetName(typeof(StaticDicdictionary.TypeDicdictionary), myCode); //获取名称
                        int num = myCode; //获取值
                        _typesenum.Add(strName, num);
                    }
                }
                return _typesenum;
            }
            set
            {
                _typesenum = value;
                RaisePropertyChanged("Types");
            }
        }

        /// <summary>
        /// 序列化数据
        /// </summary>
        /// <param name="ParentId">父ID</param>
        /// <param name="infos">序列化后的数据</param>
        private void Structuring(int ParentId, ObservableCollection<TreeViewEntity> infos)
        {
            foreach (ConfigTreeInfo info in Datas)
            {
                if (info.ParentId == ParentId)
                {

                    ObservableCollection<TreeViewEntity> temps = new ObservableCollection<TreeViewEntity>();
                    Structuring(info.Code, temps);
                    TreeViewEntity temp = new TreeViewEntity() { Data = info, DataSon = temps };
                    temp.PropertyChanged +=
                        new System.ComponentModel.PropertyChangedEventHandler(TVN_PropertyChanged);
                    infos.Add(temp);
                }
            }
        }


        /// <summary>
        /// 按类型划分数据
        /// </summary>
        /// <param name="result"></param>
        /// <param name="infos"></param>
        private void Classify(ObservableCollection<TreeViewEntity> result, ObservableCollection<TreeViewEntity> infos)
        {
            foreach (int myCode in Enum.GetValues(typeof (StaticDicdictionary.TypeDicdictionary)))
            {
                string str = Enum.GetName(typeof (StaticDicdictionary.TypeDicdictionary), myCode); //获取名称
                TreeViewEntity temp = new TreeViewEntity();
                ConfigTreeInfo cti = new ConfigTreeInfo() { Code = myCode, AssistantCode = "", Name = str, Type = -1, Sequence = -1, IsUpdate = false, ParentId = -1, MultiLevel = true, Content = "", Level = 1 };
                temp.Data = cti;
                temp.PropertyChanged +=
                      new System.ComponentModel.PropertyChangedEventHandler(TVN_PropertyChanged);
                foreach (TreeViewEntity tve in infos)
                {
                    ConfigTreeInfo cti1 = tve.Data as ConfigTreeInfo;
                    if (myCode == cti1.Type)
                    {
                        temp.DataSon.Add(tve);
                    }
                }

                result.Add(temp);
            }

        }

        public DictManagerViewModel()
            
        {
            Query();
            var a = StaticDicdictionary.TreeDicdictionary;
        }

        /// <summary>
        /// 更改选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TVN_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            SelectData = (TreeViewEntity)sender;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        private void Query()
        {
            Datas = new ConfigTreeInfo().ExtGetAll().OrderBy(p => p.Type); ;
            Nodes = new ObservableCollection<TreeViewEntity>();
            Structuring(0, Nodes);

            NodeDatas = new ObservableCollection<TreeViewEntity>();
            Classify(NodeDatas, Nodes);
        }


        public DelegateCommand OkCommand
        {
            get { return MainViewModel.Instance.ReturnToStartCommand; }
        }


        //添加节点
        private DelegateCommand _addCommand;

        public DelegateCommand AddCommand
        {
            get
            {
                if (_addCommand == null)
                    this._addCommand = new DelegateCommand(
                        () =>
                        {
                            if (SelectData != null)
                            {
                                AddFuc(false);
                            }
                        });
                return _addCommand;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="IsRoot">是否为根节点。true：根节点。false：子节点</param>
        private void AddFuc(bool IsRoot)
        {
            IsRoot = ((ConfigTreeInfo) SelectData.Data).Type == -1;
 
            if (TempInfo.Name.Trim() != "")
            {
                try
                {
                    int pid = 0;
                    int num = 0;
                    short level = 0;
                    if (IsRoot)
                    {


                    }
                    else
                    {
                        if (((ConfigTreeInfo)SelectData.Data).IsUpdate ?? true)
                        {
                            pid = ((ConfigTreeInfo)SelectData.Data).Code;
                            num = SelectData.DataSon.Count + 1;
                            ((ConfigTreeInfo)SelectData.Data).MultiLevel = true;
                            level = ((ConfigTreeInfo)SelectData.Data).Level ?? 0;
                        }
                        else
                        {
                            ShowMsg("此内容无法修改!",false);
                            return;
                        }
                    }

                    ConfigTreeInfo temp = new ConfigTreeInfo()
                                              {
                                                  Name = TempInfo.Name,
                                                  Content = TempInfo.Content,
                                                  Level = level,
                                                  Sequence = num,
                                                  Type = TempInfo.Type,
                                                  IsUpdate = true,
                                                  AssistantCode = TempInfo.AssistantCode ?? " ",
                                                  ParentId = pid,
                                                  MultiLevel = false
                                              };
                    temp.ExtAdd();
                    Query();
                    ShowMsg("添加成功!");
                }
                catch { }
            }
            else
            {
               ShowMsg("请输入名称!",false);
            }


        }

        //更新
        private DelegateCommand _updateCommand;
        public DelegateCommand UpdateCommand
        {
            get
            {
                if (_updateCommand == null)
                    this._updateCommand = new DelegateCommand(
                        () =>
                        {
                            if (SelectData != null)
                            {
                                if (((ConfigTreeInfo)SelectData.Data).IsUpdate ?? true)
                                {
                                    try
                                    {
                                        ((ConfigTreeInfo)SelectData.Data).Name = TempInfo.Name;
                                        ((ConfigTreeInfo)SelectData.Data).AssistantCode = TempInfo.AssistantCode ?? "";
                                        ((ConfigTreeInfo)SelectData.Data).Content = TempInfo.Content;
                                        ((ConfigTreeInfo)SelectData.Data).Type = TempInfo.Type;
                                        ((ConfigTreeInfo)SelectData.Data).IsUpdate = TempInfo.IsUpdate;
                                        ((ConfigTreeInfo) SelectData.Data).ExtUpdate(); 
                                        ShowMsg("修改成功!");
                                    }
                                    catch { }
                                }
                                else
                                {
                                    ShowMsg("此内容无法修改!",false);
                                }
                            }

                        });
                return _updateCommand;
            }
        }
        //删除
        private DelegateCommand _delectCommand;
        public DelegateCommand DelectCommand
        {
            get
            {
                if (_delectCommand == null)
                    this._delectCommand = new DelegateCommand(
                        () =>
                        {
                            if (SelectData != null)
                            {
                                if (((ConfigTreeInfo)SelectData.Data).IsUpdate ?? true)
                                {
                                    try
                                    {
                                        ((ConfigTreeInfo) SelectData.Data).ExtDelete(); 
                                        DeletedSonNode(SelectData.DataSon); 
                                        Query();
                                        ShowMsg("删除成功!");
                                    }
                                    catch { }
                                }
                                else
                                {
                                    ShowMsg("此内容无法修改!",false);
                                }
                            }
                        });
                return _delectCommand;
            }
        }

        /// <summary>
        /// 遍历删除子节点
        /// </summary>
        /// <param name="DataSon"></param>
        void DeletedSonNode(ObservableCollection<TreeViewEntity> DataSon)
        {
            foreach (TreeViewEntity nodeEntity in DataSon)
            {
                ((ConfigTreeInfo) nodeEntity.Data).ExtDelete(); 
                DeletedSonNode(nodeEntity.DataSon);
            }
        }

        int GetNum(ObservableCollection<TreeViewEntity> DataSon, TreeViewEntity info)
        {
            int num = -1;
            foreach (TreeViewEntity nodeEntity in DataSon)
            {
                num++;
                if (nodeEntity.Data == info.Data)
                {
                    return num;
                }
            }
            return num;
        }
    }

    public class DateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = "";
            foreach (int myCode in Enum.GetValues(typeof(StaticDicdictionary.TypeDicdictionary)))
            {
                if (int.Parse(value.ToString()) == myCode)
                {
                    str = Enum.GetName(typeof(StaticDicdictionary.TypeDicdictionary), myCode); //获取名称
                }
            }
            return str;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
